@<template>
  <div>
    <!-- 面包屑导航 -->
    <breadcrumb :breadInfo="breadInfo" />

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 提示警告区域 -->
      <el-alert
        show-icon
        :closable="false"
        title="添加商品信息"
        type="info"
        center
      >
      </el-alert>

      <!-- 步骤条 -->
      <el-steps align-center :active="activeIndex - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- form表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <!-- tabs标签部分 -->
        <el-tabs
          v-model="activeIndex"
          stretch
          tab-position="left"
          :before-leave="beforLeave"
        >
          <el-tab-pane label="基本信息" name="1">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_number">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="selectOption"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="2">
            <el-form-item :label="item.attr_name" v-for="(item, index) in goodsParams" :key="index">
            <el-checkbox-group size="small"  v-model="paramsCheckList" @change="checkParams">
             <el-checkbox checked border v-for="(p,idx) in item.attr_vals" :key="idx" :label="p"></el-checkbox>
            </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          
          <el-tab-pane label="商品属性" name="3">
            <el-form-item :label="item.attr_name" v-for="(item, index) in addForm.attrs" :key="index">
              <el-input v-model="item.attr_vals"></el-input>
            
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="商品图片" name="4">
            <el-upload
            :action="uploadURL"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :headers="headerObj"
            
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="5">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>

            <!-- 添加按钮 -->
            <el-button class="add-goods-button" type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览区域 -->
    <el-dialog
  title="图片预览"
  :visible.sync="picDialogVisible"
  width="50%"
  >
  <img :src="priviewPath" alt="">
  
</el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
import Breadcrumb from "../../common/breadcrumb/Breadcrumb.vue";
export default {
  components: {
    Breadcrumb,
  },
  data() {
    return {
      breadInfo: ["商品管理", "添加商品"],
      // 进图条当前进度
      activeIndex: "1",
      // 添加商品的表单对象
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        //商品图片
        pics: [],
        // 
        goods_introduce: '',
        goods_cat: [], //最终选择结果的数组
        attrs: []


      },
      // 表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请填入相应内容", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请填入相应内容", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请填入相应内容", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请填入相应内容", trigger: "blur" },
        ],
      },
      // 级联选择器,最终选择结果的数组
      selectKeys: [],
      //级联选择器 数据对象
      cateList: [],
      // 级联选择器 配置对象
      selectOption: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      // 商品参数
      goodsParams: [],
      //商品属性
      goodsAttr: [],
      // 商品参数多选框组
      paramsCheckList: [],
      // 商品参数多选框组
      attrCheckList: [],
      // 上传的url地址
      uploadURL: 'http://150.139.222.251:8888/api/private/v1/upload',
      // 上传图片添加的请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      // 预览的图片地址
      priviewPath: '',
      picDialogVisible: false
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("分类数据获取失败");
      this.cateList = res.data;
    },
    // 级联选择器 选中处理函数
    handleChange() {
      console.log(this.addForm.goods_cat);
    },
    beforLeave(to, from) {
      if (from == 1 && this.addForm.goods_cat.length == 0) {
        this.$message.error("请选择商品分类");
        return false;
      }

      //获取商品参数
      if (to == 2 && this.addForm.goods_cat.length == 3) {

        this.getGoodsData('many').then(res => {
         this.goodsParams = res
         console.log(this.goodsParams)
        })
        
      }

      //获取商品属性
      if(to == 3 && this.addForm.goods_cat.length == 3) {
         this.getGoodsData('only').then(res => {
          res.forEach(item => {
            item.attr_vals = item.attr_vals.join(',')
          })
         this.addForm.attrs = res
         console.log(this.addForm.attrs)

        })

      }
    },
    // 获取商品 属性 或参数
    async getGoodsData(type) {
      const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: type }})
      if (res.meta.status !== 200) return this.$message.error("获取参数失败")
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.length != 0 ? item.attr_vals.split(',') : []
      })
      return res.data
     
    },
    // 选择多选框后 触发的事件
    checkParams() {
      console.log(this.paramsCheckList)
    },
    // 图片预览的事件函数
    handlePreview(fileInfo) {
      console.log(fileInfo)
      // 拼接自己的服务器地址
      this.priviewPath = "http://xiatianweb.top:8888"+fileInfo.response.data.url.slice(21)
      console.log(this.priviewPath)

      this.picDialogVisible = true
    },  
    // 删除图片的事件函数
    handleRemove(fileInfo) {
      console.log(fileInfo)
      // 删除图片
      let picIndex = this.addForm.pics.indexOf(fileInfo.response.data.tmp_path)
      this.addForm.pics.splice(picIndex,1)
      
    },
    // 上传成功的函数
    handleSuccess(respones) {
      if (respones.meta.status !== 200) return this.$message.error("图片上传失败")
      this.addForm.pics.push(respones.data.tmp_path)
      this.$message.success("图片上传成功")
      console.log(this.paramsCheckList)
      console.log(this.attrCheckList)
    },
    // 添加商品按钮
    add() {
      console.log(this.addForm)
      // 数据预验证
      this.$refs.addFormRef.validate(valid => {
        if(!valid) return this.$message.error("请填入必填项")
        // 发起数据请求
        let newFormObj = _.cloneDeep(this.addForm)
        newFormObj.goods_cat = newFormObj.goods_cat.length != 0 ? newFormObj.goods_cat.join(',') : ''
        // newFormObj.attrs = []
        console.log(newFormObj)
        this.$http.post('goods', newFormObj).then(res => {
          console.log(res)
          if (res.data.meta.status !== 201) return this.$message.error("商品添加失败")
          this.$message.success("商品添加成功")
          // 跳转到商品页
          this.$router.push("/goods")
        })
      })
      
    }
  },
  computed: {
    cateId() {
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1];
    },
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin: 10px 50px;
}
.el-tag {
  margin: 0 5px;
}
.el-checkbox {
  margin-right: 5px;
}
img {
  width: 100%;
}
.add-goods-button {
  margin-top: 10px;
}
</style>